# _*_ coding:utf-8 _*_
# @Time  : 2022-03-29
# @Author: zizle
import time
import os
import requests

HEADERS = {
        'Accept': '*/*',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
        'Accept-Encoding': 'gzip,deflate,br',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
    }


def read_urls():
    urls = []
    with open('能源类研究方法论.m3u8', 'r') as f:
        for line in f.readlines():
            if line.startswith('http'):
                urls.append(line.strip())
    return urls


def down_load(url, file, sort_index, percent):
    try:
        r = requests.get(url, headers=HEADERS)
        content = r.content
        sort_index = '%04d' % sort_index
        with open(f'C:/Users/Administrator/Desktop/vieeo/{sort_index}-{file}', 'wb') as fp:
            fp.write(content)

    except Exception as e:
        print(url, '下载失败{}'.format(e))

    print(f'{sort_index}-{file}-下载成功! -- {percent}%')


def rename_files():
    for parent, _, filelist in os.walk('video'):

        for f in filelist:
            newname = '%04d-' % int(f.split('-')[0]) + f.split('-')[1]
            os.rename(os.path.join(parent, f), os.path.join(parent, newname))
            print(f, newname)


if __name__ == '__main__':
    all_urls = read_urls()
    length = len(all_urls)
    for index, u in enumerate(read_urls()):
        filename = u.rsplit('_', 2)[1] + '_' + u.rsplit('_', 2)[2]
        p = round((index + 1) * 100 / len(all_urls), 4)
        # print(u, '\n', filename)
        down_load(u, filename, index, p)
        time.sleep(0.5)
